"""
# -*- coding:utf-8 -*-
@Project : telegramBot
@software: PyCharm
@File : botTools.py
@author:  wade
@IDE NAME: PyCharm
@Time : 2025/6/11 13:26
@
"""
import asyncio
import platform
import threading

from serverchan_sdk import sc_send
from tools.db_connect import MySQLCRUD

# send_push key
sendkey = "sctp6765tcomfljakjcquc4e7mdaman"


class BotTools:

    async def run_shell_command(self, command: str) -> tuple:
        """
        异步执行 shell 命令，返回退出码
        """
        process = await asyncio.create_subprocess_shell(
            command,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )

        # 等待命令执行完成
        stdout, stderr = await process.communicate()
        # print(f'stdout: {stdout.decode()}\n,stderr: {stderr}')
        return process.returncode, stdout, stderr

    async def send_push_notification(self, desp: str, title: str = 'TDL', tags: str = 'TDL下载器') -> None:
        """
        异步发送推送消息到手机
        """
        res = sc_send(sendkey=sendkey, title=title, desp=desp, options={"tags": tags})
        print(res)

    async def send_push_kdw_info(self, desp: str, title: str = '蝌蚪窝详情', tags: str = "kdw"):

        res = sc_send(sendkey=sendkey, title=title, desp=desp, options={"tags": tags})

    async def tdl_download(self, urls):
        # 执行 shell 命令（示例：异步压缩文件夹）
        print('Downloading content from URL:', )
        for url in urls:
            print(url)
            if platform.system() == "Linux":
                command = f"tdl dl --takeout -d /root/tdl_download -u {url}"
            elif platform.system() == "Darwin":
                command = f"tdl dl --takeout -d /Users/wade/Downloads/TelegramDownload/tdlDownload -u {url}"
            exit_code, stdout, stderr = await self.run_shell_command(command)
            # 根据退出码发送通知
            print('执行结果：', exit_code, stdout, stderr)
            video_name = stdout.decode('utf-8').rsplit('34m')[-3]

            if exit_code == 0:
                await self.send_push_notification(desp=f"下载完成✅：{video_name}", title="TDL下载器")
            else:
                await self.send_push_notification("❌Shell 命令执行失败 ", title="TDL下载器")

    def run_tdl(self, urls):
        thread = threading.Thread(target=self.tdl_download, args=(urls,))  # args 是元组
        thread.start()

    async def get_video(self, name):
        return f'kdw视频:{name}'
